package com.fzebu.fastboot.form.converter.impl;

import com.alibaba.fastjson.JSONObject;
import com.fzebu.fastboot.form.converter.AbstractProcessHandler;
import com.fzebu.fastboot.form.converter.FormConverter;
import com.fzebu.fastboot.form.exception.ConvertException;
import weaver.conn.RecordSetTrans;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/1/26 23:17
 */
public class DbFormHandler extends AbstractProcessHandler {

    @Override
    public void initialize(FormConverter.Builder builder) {
        super.initialize(builder);
        if (builder.getRst() == null) {
            throw new IllegalArgumentException("RecordSetTrans is null");
        }
    }

    @Override
    public Object toJavaBean() throws ConvertException {
        if (builder.getRst().next()) {
            return toBean(new JSONObject());
        }
        return null;
    }

    @Override
    public List<Object> toJavaArray() throws ConvertException {
        RecordSetTrans rst = builder.getRst();
        List<Object> list = new ArrayList<>(rst.getCounts());
        while (rst.next()) {
            list.add(toBean(new JSONObject()));
        }
        return list;
    }

    private Object toBean(JSONObject json) throws ConvertException {
        RecordSetTrans rst = builder.getRst();
        for (String colName : rst.getColumnName()) {
            this.putValue(json, colName, rst.getString(colName));
        }
        return this.toJavaBean(json);
    }
}
